<?php

/**
* 股票交易
*
* @package		Hooloo framework
* @author 		Bill
* @copyright 	Hooloo Co.,Ltd
* @version		1.0
* @release		2017.05.08
*/
defined('BASEPATH') OR exit('No direct script access allowed');

class Stock extends Controller{
	public function __construct(){
		parent::__construct();
	}
	
	/**
     * 资金股票
     */
	public function index($p = 1) {
		//查询条件
		$uid = $_SESSION["user"]["id"];
		$begin_time = strtotime(date("Y-m-d 09:00:00", strtotime("-10 day")));
		$end_time = time();
		$where = " where uid = $uid and can_sell = 1";

		//查询总数
		$sql = "select count(*) c from stock_bull " . $where;
		$total = $this->db->query($sql)->row_array();
		$total = $total["c"];
		
		//数据分页
		$pize = 15;//每页数量
		if (is_mobile()) $pize = 10000;
		if(0 >= $p){
			$p = 1;
		}
		$start = ($p - 1) * $pize;//分页开始
		
		//分页查询
		$sql = "select id, stock_type, stock_code, stock_name, bull_type, bull_num, bull_cost_money, sell_num, can_sell_num, bull_price, bull_money, bull_time, bull_trust_id, concat(stock_type, stock_code) as stock from stock_bull " . $where . " order by bull_time desc limit $start, $pize";
		$list = $this->db->query($sql)->result_array();
		
		//分页展示
		$url = "/" . $this->_controller . "/" . $this->_action . "/";
		$page = page_format($total, $pize, $p, $url);

		//分配变量
		$this->assign("list", $list);
		$this->assign("total", $total);
		$this->assign("page", $page);
		$this->display();
	}

	/**
     * 用户委托
     */
	public function trust($start_time = 0, $end_time = 0, $p = 1) {
		//查询条件
		$uid = $_SESSION["user"]["id"];

		//搜索时间
		if (! $start_time) $start_time = date("Y-m-d"); 
		if (! $end_time) $end_time = date("Y-m-d");
		if ($start_time > $end_time) $this->error("开始时间不能大于结束时间！");
		$where = "where uid = $uid and stock_trust_time >= '".strtotime($start_time)."' and stock_trust_time <= '".strtotime($end_time . " 23:59:59")."'";
		
		//查询总数
		$sql = "select count(*) c from stock_trust " . $where;
		$total = $this->db->query($sql)->row_array();
		$total = $total["c"];
		
		//数据分页
		$pize = 15;//每页数量
		if(0 >= $p){
			$p = 1;
		}
		$start = ($p - 1) * $pize;//分页开始
		
		//分页查询
		$sql = "select id, stock_trust_time, FROM_UNIXTIME(stock_trust_time) trust_time, stock_deal_time, stock_code, stock_name, bull_type, trust_type, price, num, status, concat(stock_type, stock_code) as stock from stock_trust " . $where . " order by id desc limit $start, $pize";
		$list = $this->db->query($sql)->result_array();
		
		//分页展示
		$url = "/" . $this->_controller . "/" . $this->_action . "/" . $start_time . "/". $end_time . "/";
		$page = page_format($total, $pize, $p, $url);
		
		//分配变量
		$this->assign("list", $list);
		$this->assign("total", $total);
		$this->assign("page", $page);
		$this->assign("begin_time", $start_time);
		$this->assign("end_time", $end_time);
		$this->display();
	}
	
	/**
     * 交割单
     */
	public function delivery($start_time = 0, $end_time = 0, $p = 1) {
		//查询条件
		$uid = $_SESSION["user"]["id"];

		//搜索时间
		if (! $start_time) $start_time = date("Y-m-d"); 
		if (! $end_time) $end_time = date("Y-m-d");
		if ($start_time > $end_time) $this->error("开始时间不能大于结束时间！");
		$where = " where uid = $uid and sell_time >= " . strtotime($start_time) . " and sell_time <= " . strtotime($end_time . " 23:59:59");
		
		//数据分页
		$pize = 15;//每页数量
		if(0 >= $p){
			$p = 1;
		}
		$start = ($p - 1) * $pize;//分页开始

		//查询总数
		$sql = "select count(*) c, sum(gain) gain,  sum(round(((sell_num * bull_price) * 0.003), 2) + cost_money) cost, sum(save_money + stamp_money + manage_money) save_money from stock_sell " . $where;
		$count = $this->db->query($sql)->row_array();
		$total = $count["c"];
		$total_gain = $count["gain"] - $count["cost"] - $count["save_money"];
		
		//查询记录
		$sql = "select *, FROM_UNIXTIME(bull_time) b_time, FROM_UNIXTIME(sell_time) s_time, concat(stock_type, stock_code) as stock from stock_sell" . $where . " order by bull_time desc limit $start, $pize";
		$list = $this->db->query($sql)->result_array();
		//计算盈亏
		foreach ($list as $key => $val) {
			$list[$key]["cost"] = $val['cost_money'] + round(($val['bull_price'] * $val["sell_num"]) * 0.003, 2);//手续费：买入手续费 + 卖出手续费
			//盈亏：卖出后收益 - 手续费 - 留仓费 - 印花税 - 管理费
			$list[$key]["total_gain"] = $val["gain"] - $list[$key]["cost"] - $val["save_money"] - $val["stamp_money"] - $val["manage_money"];
		}

		//分页展示
		$url = "/" . $this->_controller . "/" . $this->_action . "/" . $start_time . "/". $end_time . "/";
		$page = page_format($total, $pize, $p, $url);

		$this->assign("list", $list);
		$this->assign("total", $total);
		$this->assign("page", $page);
		$this->assign("begin_time", $start_time);
		$this->assign("end_time", $end_time);
		$this->assign("total_gain", $total_gain);
		
		IS_AJAX && ajax_return(1, "查询成功", $list);
		$this->display();
	}
	
	/**
     * 购买股票
     */
	public function bull() {
		$uid = $_SESSION["user"]["id"];
		if (IS_POST) {
			//接收参数
			$code = isset($_POST["stock_code"]) ?  $_POST["stock_code"] : "";
			
			//查询股票
			$sql = "select id from stock_code where code = '$code'";
			$row = $this->db->query($sql)->row_array();
			if ($row) {
				//接收参数
				$bull_num = isset($_POST["bull_num"]) ?  (int)$_POST["bull_num"] : 0;
				$bull_price = isset($_POST["bull_price"]) ?  round($_POST["bull_price"], 2) : 0;
				$bull_type = isset($_POST["bull_type"]) ?  (int)$_POST["bull_type"] : 1;
				$price_type = isset($_POST["price_type"]) ?  (int)$_POST["price_type"] : 0;
				
				//设置参数
				if ($price_type != 1) $price_type = 0;
				if ($price_type == 0)	$bull_price = 0;

				//购买股票
				$result = bull_stock($uid, $code, $bull_num, $bull_type, $bull_price);
				
				//返回购买结果
				ajax_return($result["status"], $result["msg"], "/stock/index");
			} else {
				ajax_return(0, "股票代码不正确");
			}
		}
		
		//获取用户信息
		$user = get_user($uid);
		$this->assign("user", $user);
		$this->display();
	}
	
	/**
     * 强制平仓
     */
	public function ajax_set_sell() {
		if (IS_POST) {
			//接收参数
			$id = isset($_POST["id"]) ? (int)$_POST["id"] : 0;
			$num = isset($_POST["sell_num"]) ? (int)$_POST["sell_num"] : 0;
			$sell_price = isset($_POST["sell_price"]) ? round($_POST["sell_price"], 2) : 0;
			$price_type = isset($_POST["price_type"]) ? intval($_POST["price_type"]) : 0;
			if ($price_type != 1) $price_type = 0;
			if ($price_type == 0) $sell_price = 0;

			//卖出股票（强制）
			$result = sell_stock($id, $num, $sell_price);

			//返回卖出
			ajax_return($result["status"], $result["msg"]);
		}
	}
	
	/**
     * 撤销委托单
     */
	public function ajax_set_trust() {
		if (IS_POST) {
			//接收参数
			$id = isset($_POST["id"]) ? (int)$_POST["id"] : 0;
			$trust_type = isset($_POST["trust_type"]) ? (int)$_POST["trust_type"] : 0;
			
			//执行操作
			$result = common_trust($id, $trust_type);
			
			//返回卖出
			ajax_return($result["status"], $result["msg"]);
		}
	}
	
	/**
     * 持仓单-最新价格
     */
	public function ajax_get_bull() {
		if (IS_AJAX) {
			//接收参数
			$uid = $_SESSION["user"]["id"];
			$bull_id = isset($_POST["data"]) ? trim(sql_format($_POST["data"]), ",") : "";
			$result = array();
			
			//校验参数
			if ($bull_id) {
				//查询记录
				$sql = "select id bull_id, aid, uid, username, stock_type, stock_code, stock_name, can_sell_num, bull_type, bull_price, bull_time, bull_num, sell_num, bull_cost_money, concat(stock_type, stock_code) as code from `stock_bull` where id in ($bull_id) and uid = $uid";
				$list = $this->db->query($sql)->result_array();
				
				//判断记录是否存在
				if ($list) {
					//股票行情
					$stock_info = array_column($list, "code");
					$stock_info = get_stock($stock_info);

					//计算浮盈
					foreach ($list as $key => $val) {
						//股票最新价格，如果停盘交易价格按照昨天收盘价格收盘
						$sell_price = round($stock_info[$val["code"]][3], 2);
						if ($sell_price <= 0) {
							$sell_price = round($stock_info[$val["code"]][2], 2);
							$disable = 1;
						} else {
							$disable = 0;
						}
						
						//设置参数
						$data["price"] = $sell_price;//卖出价格
						$data["num"] = $val["bull_num"] - $val["sell_num"];//卖出数量（考虑委托）
						$data["bull_type"] = $val["bull_type"];//股票类型1-融资，2-融券
						$data["bull_price"] = $val["bull_price"];//买入价格
						$data["stock_code"] = $val["stock_code"];//股票代码
						$data["bull_time"] = $val["bull_time"];//建仓时间
						
						//计算卖出
						$sell = common_sell($data);
	
						//组装参数
						$result[$val["bull_id"]]["price"] = number_format($sell_price, 2);//当前价格
						$result[$val["bull_id"]]["save"] = number_format($sell["save_money"], 2) . "/" . $sell["save_day"] . "天";
						$result[$val["bull_id"]]["total_gain"] = $sell["total_gain"];//浮动总盈亏
						$result[$val["bull_id"]]["gain"] = $sell["gain"];//浮动盈亏
						$result[$val["bull_id"]]["manage_money"] = number_format($sell["manage_money"], 2);//管理费金额
						$result[$val["bull_id"]]["can_sell"] = $disable;//是否可以卖
						$result[$val["bull_id"]]["loss"] = number_format($sell["loss"], 2);//盈亏比例
					}
				}
			}
			//返回结果
			ajax_return(1, "SUCCESS", $result);
		}
	}
	
	/**
     * 委托单-最新价格
     */
	public function ajax_get_trust() {
		if (IS_AJAX) {
			//接收参数
			$uid = $_SESSION["user"]["id"];
			$trust_id = isset($_POST["data"]) ? trim(sql_format($_POST["data"]), ",") : "";
			$result = array();
			
			//校验参数
			if ($trust_id) {
				//查询记录
				$sql = "select id, stock_code, status, stock_type, stock_deal_time, CONCAT(stock_type, stock_code) as code from stock_trust where id in ($trust_id) and uid = $uid";
				$list = $this->db->query($sql)->result_array();
				
				//判断记录是否存在
				if ($list) {
					//股票行情
					$stock_info = array_column($list, "code");
					$stock_info = get_stock($stock_info);
					
					//计算浮盈
					foreach ($list as $key => $val) {
						$result[$val["id"]]["status"] = $val["status"];
						if ($val["status"] == 0) {
							$result[$val["id"]]["price"] = number_format($stock_info[$val["code"]][3], 2);
							$result[$val["id"]]["stock_deal_time"] = "--";
						} else {
							$result[$val["id"]]["price"] = "--";
							$result[$val["id"]]["stock_deal_time"] = date("Y-m-d H:i:s", $val["stock_deal_time"]);
						}
					}
				}
			}
			
			//返回结果
			ajax_return(1, "SUCCESS", $result);
		}
	}
	
	/**
     * 股票信息
     */
	public function ajax_get_stock() {
		if (IS_AJAX) {
			//接收参数
			$code = isset($_POST["code"]) ?  $_POST["code"] : "";
			if ($code) {
				//查询股票
				$sql = "select CONCAT(type, code) as code from stock_code where code = '$code'";
				$row = $this->db->query($sql)->row_array();
				if ($row) {
					//股票信息
					$result = get_stock(array($row["code"]));
					
					//返回结果
					ajax_return(1, "SUCCESS", $result[$row["code"]]);
				}
				
			}
			ajax_return(0, "不支持股票交易代码");
		}
	}
}
